#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXNICKNAMESIZE 30

#define NICK 1

typedef struct nickname{
    char * name;
    struct nickname * next;
    struct nickname * prev;
} nickname_t;

typedef nickname_t * nickname_ptr;

nickname_ptr new_nickname(char * nick){
    nickname_ptr new = malloc(sizeof(nickname_t));
    if (new == NULL){
        exit(1);
    }
    new->name = nick;
    new->next = NULL;
    new->prev = NULL;

    return new;
}

nickname_ptr add_nickname(nickname_ptr nick, nickname_ptr list){
    nickname_ptr p;

    for (p = list; p->next != NULL; p = p->next){
        if (strcmp(p->name, nick->name) > 0){ /* nick-> name > p->name */

        }
        else if (strcmp(p->name, nick->name)){ /* nick->name < p->name */
        }
        else{ /* nick->name já existe na lista =( */
            return NULL;
        }
    }
}

int get_command(char *cmd){
    if (strcmp("nick", cmd) == 0)
        return NICK;
    return 0;
}


char * set_nickname(int sockfd, struct sockaddr_in cliaddr){
    char * prompt = "Digite seu nickname (com até 30 caracteres) : ";
    sendto(sockfd, prompt, strlen(prompt), 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
/*    if (add_nickname() == NULL){  nickname inválido
        return NULL;
    }*/
    return prompt;
}


int main(int argc, char**argv)
{
    int sockfd,n;
    struct sockaddr_in servaddr,cliaddr;
    socklen_t len;
    char buffer[1000];
    char mesg[1000];
    char * nicknames_list;
    char * inic_msg = "Bem vindo ao chat! Escolha um nickname de até 30 caracteres : ";

    int i;
    
    sockfd=socket(AF_INET,SOCK_DGRAM,0);


    memset(&servaddr, (char) 0, sizeof(servaddr));

/*    bzero(&servaddr,sizeof(servaddr));*/
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
    servaddr.sin_port=htons(32000);
    bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
    
    for (;;) {
        len = sizeof(cliaddr);

        printf ("1\n");

        sendto(sockfd,inic_msg,strlen(inic_msg),0,(struct sockaddr *)&cliaddr,sizeof(cliaddr)); /* envia mensagem para cliente */

        printf ("2\n");
        n = recvfrom(sockfd,buffer,1000,0,(struct sockaddr *)&cliaddr,&len);
        printf ("3\n");
            for (i = 0; i < n - 1; i++){ /* limpa entrada, pegando somente a mensagem */
            mesg[i] = buffer[i];
        }       
        mesg[n] = '\0';

        printf ("4\n");
        if (get_command(mesg) == NICK){
/*            nickname = set_nickname(sockfd, cliaddr);*/
        }
    }
}
